import math
import pymysql

from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib import auth
from django.shortcuts import render, render_to_response
# Create your views here.
from django.shortcuts import HttpResponse
from django.utils.safestring import mark_safe
from django.views.decorators.csrf import csrf_exempt
from pyecharts import Line3D, Line, Geo, WordCloud

from cmdb.models import AnminatonPic, AdminUser, AnminatonWinPic, AnminationWinArt, DNFPrice, pc, Movie,Book


@csrf_exempt
def login(request):
    if request.POST:
        name=request.POST['username']
        password=request.POST['password']
        # if AdminUser.objects.filter(name=name,password=password):
        #     request.session['name'] = name
        #     return render_to_response('index.html')
        user = auth.authenticate(username=name, password=password)
        if user is not None:
            if user.is_active:
                auth.login(request, user)
                return render_to_response('index.html')
            else:
                print("密码错误")
        else:
            print('用户名或密码错误')
    return render_to_response('login.html')
@login_required
def index(request):
    # if request.session.get('name',-1)!=-1:
        request.session['page'] = 0
        list = AnminatonPic.objects.order_by('id')[0:30]
        count=AnminatonPic.objects.all().count()

        return render(request, 'index.html', {"data":list,"count":count,"percent":int(30/count*100)})

    # return render_to_response('login.html')

def domysql(request):
    test=AdminUser(name='测试1',password='htsfsgfdggdsgf')
    test.save()
    return HttpResponse("Hello world ! ")
@login_required
def clearSession(request):
    auth.logout(request)
    return render_to_response('login.html')

@login_required
def pashu(request):

        return render_to_response('index.html')

@login_required
def fanye(request):

        page=request.session.get('page', -1)+30
        list = AnminatonPic.objects.order_by('id')[page:page+30]
        count = AnminatonPic.objects.all().count()
        request.session['page'] = page
        return render(request, 'index.html', {"data":list,"count":count,"percent":int(30/count*100)})


@login_required
def rfanye(request):

        if request.session.get('page', -1)>0:
            page = request.session.get('page', -1) - 30
            list = AnminatonPic.objects.order_by('id')[page:page + 30]
            count = AnminatonPic.objects.all().count()
            request.session['page'] = page
            return render(request, 'index.html', {"data": list,"count":count,"percent":int(30/count*100)})

@login_required
def winpic(request):

        request.session['pagewin'] = 0
        list = AnminatonWinPic.objects.order_by('id')[0:30]
        count = AnminatonWinPic.objects.all().count()

        return render(request, 'winpic.html', {"data": list, "count": count, "percent": int(30 / count * 100)})


@login_required
def fanyewin(request):

        page=request.session.get('pagewin', -1)+30
        list = AnminatonWinPic.objects.order_by('id')[page:page+30]
        count = AnminatonWinPic.objects.all().count()
        request.session['pagewin'] = page
        return render(request, 'winpic.html', {"data":list,"count":count,"percent":int(30/count*100)})


@login_required
def rfanyewin(request):

        if request.session.get('pagewin', -1)>0:
            page = request.session.get('pagewin', -1) - 30
            list = AnminatonWinPic.objects.order_by('id')[page:page + 30]
            count = AnminatonWinPic.objects.all().count()
            request.session['pagewin'] = page
            return render(request, 'winpic.html', {"data": list,"count":count,"percent":int(30/count*100)})


@csrf_exempt
def reg(request):
    if request.POST:
        name = request.POST['username']
        password = request.POST['password']
        # test = AdminUser(name=name, password=password)
        # test.save()
        user = User.objects.create_user(name,"36043243@qq.com",password)
        user.save()

    return render_to_response('login.html')

@login_required
def winMenuDetail(request):
    if request.GET:
        id=request.GET['id']
        article=AnminationWinArt.objects.get(id=id)
        pageHtml = mark_safe(article.content)
        return render(request, 'win-menu-delete.html', {"article": pageHtml})

@login_required
def winMenu(request):
    article = AnminationWinArt.objects.order_by('id')[0:30]
    return render(request, 'winMenu.html',{"article": article})

REMOTE_HOST = "https://pyecharts.github.io/assets/js"


def linfDetail(request):
    if request.GET:
        id=request.GET['id']
        article=pc.objects.get(id=id)
        linfpageHtml = mark_safe(article.sign)
        linfpageHtml1 = mark_safe(article.href)
        return render(request, 'linf-delete.html', {"article": linfpageHtml,"video":linfpageHtml1})

def linf(request):
    names = pc.objects.order_by('id')[0:30]
    return render(request, 'linf.html', {"names": names})

def movieDetail(request):
    if request.GET:
        id = request.GET['id']
        art =Movie.objects.get(id=id)
        moviepageHtml = mark_safe(art.intro)
        return render(request, 'movie-delete.html', {"art": moviepageHtml})

def movie(request):
        art = Movie.objects.order_by('id')[0:30]
        return render(request, 'movie.html', {"art": art})
def chart(request):
    l3d = line3d()
    context = dict(
        myechart=l3d.render_embed(),
        host=REMOTE_HOST,
        script_list=l3d.get_js_dependencies()
    )

    return render(request, 'chart.html',context)
def line3d():
    list6 = DNFPrice.objects.filter(server=6)
    v1=[var.price for var in list6]
    attr = [var.date for var in list6]
    # attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
    # v1 = [5, 20, 36, 10, 10, 100]

    # list5 = DNFPrice.objects.filter(server=5)
    #
    # v2 = [var.price for var in list5]
    # attrv2 = [var.date for var in list5]

    # v2 = [55, 60, 16, 20, 15, 80]
    line = Line("DNF金币价格分析")
    line.add("跨6",
             attr, v1,
             mark_point=['max',"average",'min'],
             is_stack=True,
             is_label_show=True,
             xaxis_name='时间',
             yaxis_name='/万金币'
             )
    # line.add("商家B", attrv2, v2, is_smooth=True, mark_line=["max", "average"])
    line.render()


    return line

# def testMap():
#     data = [
#         ("三亚市", 11)]
#     geo = Geo("全国主要城市空气质量", "data from pm2.5", title_color="#fff",
#               title_pos="center", width=1000,
#               height=600, background_color='#404a59')
#     attr, value = geo.cast(data)
#     geo.add("", attr, value, visual_range=[0, 200], maptype='china', visual_text_color="#fff",
#             symbol_size=10, is_visualmap=True)
#     geo.render()  # 生成html文件
#     return geo

def book(request):
    # conn = pymysql.connect(
    #     host='localhost', user='root', password="admin",
    #     database='python', port=3306,
    #     charset='utf8'
    # )
    # cursor = conn.cursor()
    # sql_select = "select bookname,pic from book"
    # cursor.execute(sql_select)
    # xinxi = cursor.fetchall()
    # booka = []
    # for i in xinxi:
    #     # print(i[0],':',i[1],':',i[2],':',i[3])
    #     a = {'name': '', 'src': ''}
    #     a['name'] = i[0]
    #     a['src'] = i[1]
    #     booka.append(a)
    listbook = Book.objects.order_by('id')
    return render(request,"book.html",{"listbook":listbook})

def bookDeail(request):
    if request.GET:
        id = request.GET['id']
        bookdetail=Book.objects.get(id=id)
        # bookname = mark_safe(bookdetail.bookname)
        # bookpic=  mark_safe()
        return render(request, 'bookDetail.html', {"bookname": bookdetail.bookname,"bookpic":bookdetail.pic})

def bookSearch(request):
    if request.GET:
        name=request.GET['name']
        booklist=Book.objects.filter(bookname__contains=name)
        if booklist:
            return render(request, "booksearch.html", {"booklist": booklist})
        else:
            nobook='没有查到这条记录,请重新搜索'
            return render(request, "booksearch.html", {"nobook": nobook})
# def ciyun():
#     name = [
#         'Sam S Club', 'Macys', 'Amy Schumer', 'Jurassic World', 'Charter Communications',
#         'Chick Fil A', 'Planet Fitness', 'Pitch Perfect', 'Express', 'Home', 'Johnny Depp',
#         'Lena Dunham', 'Lewis Hamilton', 'KXAN', 'Mary Ellen Mark', 'Farrah Abraham',
#         'Rita Ora', 'Serena Williams', 'NCAA baseball tournament', 'Point Break']
#     value = [
#         10000, 6181, 4386, 4055, 2467, 2244, 1898, 1484, 1112,
#         965, 847, 582, 555, 550, 462, 366, 360, 282, 273, 265]
#     wordcloud = WordCloud(width=1300, height=620)
#     wordcloud.add("", name, value, word_size_range=[20, 100])
#     wordcloud.render()
#     return wordcloud